<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AdminUsersRelatedModel;
use App\Models\CustomerFollowRecordModel;
use App\Models\CustomerModel;
use App\Models\TaskUserModel;
use App\Models\TaskUserRelatedRecordModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        $user = AdminUsersRelatedModel::query()
            ->leftJoin('admin_users', 'admin_users.id', '=', 'admin_users_related.user_id');
        if (ISADMIN) $user->where('admin_users_related.main_id', '>', 0);
        else {
            if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) {
                $user->orWhere('admin_users_related.main_id', MAINID)
                    ->orWhere('user_id', MAINID);
            }
            else $user->where('admin_users_related.user_id', USERID);
        }
        $user = $user->pluck('name', 'user_id')->toArray();

        $arr = [];
        foreach ($user as $key => $value) {
            $arr[] = [
                'id' => $key,
                'name' => $value,
                'total_count' => CustomerModel::query()->where('operator_id', $key)->count(),
                'today_count' => CustomerModel::query()->where('operator_id', $key)->whereDate('created_at', date('Y-m-d'))->count(),
                'customer_follow_count' => CustomerFollowRecordModel::query()->where('operator_id', $key)->whereDate('date', date('Y-m-d'))->sum('times'),
                'task_follow_count' => TaskUserRelatedRecordModel::query()->where('operator_id', $key)->whereDate('date', date('Y-m-d'))->sum('times'),
            ];
        }

        return Admin::content(function (Content $content) use ($user, $arr) {
            $content->description('首页');
            $content->body(view('index.index', [
                'data' => $arr,
                'user' => $user,
            ]));
        });
    }

    public function hello(Content $content): Content
    {
        return $content->title('hello')->description('hello');
    }
}
